package com.yzg.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author misterWei
 * @create 2020年05月13号:14点08分
 * @mailbox forcontinue@163.com
 * 可打断的锁
 */
@Slf4j(topic = "c.lockInterrupt")
public class LockInterrupt {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread l1 = new Thread(() -> {
            try {
                log.debug("锁开始竞争");
                lock.lockInterruptibly();
                log.debug("锁被拿到了.");
            } catch (InterruptedException e) {
                log.debug("锁被打断了.");
                //此处一定记得return,
                // 否则线程持有的锁已经状态发生改变,
                // 在调用下面临界区代码就会有问题,monitor就不存在.
                return;
            }

            try {
                //临界区代码
            } finally {
                lock.unlock();
            }

        }, "l1");
        lock.lock();
        l1.start();
        Thread.sleep(2000L);
        //进行打断其它线程对锁的持有
        l1.interrupt();
    }
}
